(function(){

    var bgColorDefault = '#fff';
    var bgColorSelect  = '#fff'; //'#cfc';
    var myMixiFullList = new Array();
    var dateArray      = new Array();
    var selectedGroup  = 0;
    var ownerInfo;

    jQuery(function($) {
        $(window).autoHeight();
        var now = new Date();
        for (var i = 0; i < 2; i++) {
            var tempDate = new Date(now.getFullYear(), now.getMonth(), now.getDate() + i);
            var year  = tempDate.getFullYear();
            var month = tempDate.getMonth() + 1;
            var date  = tempDate.getDate();
            if (month < 10) { month = '0' + month; }
            if (date  < 10) { date  = '0' + date;  }
            dateArray.push(year + '-' + month + '-' + date);
        }
        
        $.parallel([
            $.getData('/people/@owner/@self'  , {}),
            $.getData('/people/@owner/@friends/@app', { startIndex: 0, count: 100 })
        ])
        .next(function(data){
            var owner   = data[0];
            var friends = data[1];

            ownerInfo  = owner[0];
            var memberIdList = new Array();
            $.each(friends, function(i, person) {
                myMixiFullList['m'+person.id] = person;
                memberIdList.push(person.id);
            });
            if (memberIdList.length) {
                var memberIdStr = memberIdList.join('-');
                getSchedule(memberIdStr);
            }
        })
        .error(function(e){
            //console.log(''+e);
        });
        
        $('#send_feed').click(function(){
            if (!$('#feed_message').val()) {
                alert('お誘いを記入してください。');
                return;
            }
            var message = $('#feed_message').val();
            var recipients = new Array();
            $('.hima_list').eq(selectedGroup).children().each(function(){
                if ($('.selected', this).text() == 1)
                    recipients.push($('.id', this).text());
            });
            if (!recipients.length) {
                alert('相手を選択してください。');
                return;
            }
            $('.hima_list').children().css('background-color', bgColorDefault);
            $('.selected').text(0);
            $('#feed_message').val('');
        });
        
        $('#link_to_canvas').click(function(){
            var view = gadgets.views.getSupportedViews()["canvas"];
            gadgets.views.requestNavigateTo(view);
        });
    });
    
    function getSchedule (memberIdStr) {
        var apiUrl = apiUrlPrefix + 'schedule_select_list.php?member_id=' + memberIdStr +
            '&start_date=' + dateArray[0] + '&end_date=' + dateArray[1] + '&check=0&stamp=' + (new Date).getTime();
        //alert(apiUrl);
        var params = {};
        if (isRelease) params[gadgets.io.RequestParameters.AUTHORIZATION] = gadgets.io.AuthorizationType.SIGNED;
        params[gadgets.io.RequestParameters.CONTENT_TYPE] = gadgets.io.ContentType.JSON;
        gadgets.io.makeRequest(apiUrl, function(ret){
            if (!ret || !ret.data || ret.data.return_code != 0) {
                //alert('スケジュールの取得に失敗しました');
                return;
            }
            $.each(ret.data.result, function(i, schedule){ drawSchedule(schedule) });
        }, params);
        return;
    }
    
    function drawSchedule (schedule) {
        if (!schedule) return;
        var index = $.inArray(schedule.start_date, dateArray);
        var area = $('.hima_list').eq(index);
        var himaTmpl = $('#schedule_tmpl').clone().show().appendTo(area);
        $('.nobody', area).remove();
        $('.user_thumb', himaTmpl).attr('src', myMixiFullList['m'+schedule.member_id].thumbnailUrl).show();
        $('.id', himaTmpl).text(schedule.member_id).hide();
        $('.display_name', himaTmpl).text(myMixiFullList['m'+schedule.member_id].nickname).show();
        himaTmpl.click(function(){ addEventHandler(this) });
    }
    
    function addEventHandler (target) {
        var group = $('.hima_list').index($(target).parent());
        if (group != selectedGroup) {
            var children = $('.hima_list').eq((group + 1) % 2).children();
            children.css('background-color', bgColorDefault);
            $('.selected', children).text(0);
            selectedGroup = group;
        }
        if ($('.selected', target).text() == 0) {
            $('.selected', target).text(1);
            $(target).css('background-color', bgColorSelect);
        }
        else {
            $('.selected', target).text(0);
            $(target).css('background-color', bgColorDefault);
        }
    }
    
    function invite (memberId) {
        if (!$member_id) return;
        var today = new Date();
        var y = today.getFullYear();
        var m = today.getMonth()+1;
        var d = today.getDate();
        var targetDate = y + '-' + (m < 10 ? '0'+m : m) + '-' + (d < 10 ? '0'+d : d);
        var apiUrl = apiUrlPrefix + 'invite.php?member_id=' + membersId +
            '&date=' + targetDate + '&stamp=' + (new Date).getTime();
        extAPI(apiUrl,
            function(data){ },
            function(){ alert('お誘いの登録に失敗しました。') }
        );
    }

})();
